package edu.stanford.bmir.protege.web.server.stkosutil.common;
import java.io.BufferedReader;
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;  
import java.net.HttpURLConnection;
import java.net.URL;  
import java.net.URLConnection;  
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.logging.Level;  
import java.util.logging.Logger;  
/**
 * 此类提供了向单点服务认证服务器发送post情况的方法
 */
public class HttpClient {
	  final public static String FLAG_SUCCESS = "@@@SUCCESS:";
	  final public static String FLAG_ERROR = "@@@ERROR:";
	  
	  final public static String FIELD_SEPARATOR="~~~";
	  final public static String RECORD_SEPARATOR="@@@";
	  
	  public static String doPost(String postUrl, Hashtable<String, String> hParameters) throws AppException{
		  //String parameterData = "username=nickhuang&blog=http://www.cnblogs.com/nick-huang/";
		  try{
		  String parameterData = "";
		  if (hParameters!=null){
			 Enumeration<String> eParaNames = hParameters.keys();
			 while (eParaNames.hasMoreElements()){
				 String paraName = eParaNames.nextElement();
				 String paraValue = hParameters.get(paraName);
				 parameterData += ((parameterData.length()==0)?"":"&")
				 	+ paraName +"=" + paraValue;
			 }
		  }
	      URL localURL = new URL(postUrl);
	      URLConnection connection = localURL.openConnection();
	      HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
	      httpURLConnection.setDoOutput(true);
	      httpURLConnection.setRequestMethod("POST");
	      httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
	      httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	      httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));
	      
	      //conn.setRequestProperty("accept", "*/*");
          //conn.setRequestProperty("connection", "Keep-Alive");
          httpURLConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	      
          OutputStream outputStream = null;
	      OutputStreamWriter outputStreamWriter = null;
	      InputStream inputStream = null;
	      InputStreamReader inputStreamReader = null;
	      BufferedReader reader = null;
	      StringBuffer resultBuffer = new StringBuffer();
	      String tempLine = null;
	        
	        try {
	            outputStream = httpURLConnection.getOutputStream();
	            outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
	            outputStreamWriter.write(parameterData.toString());
	            outputStreamWriter.flush();
	            
	            if (httpURLConnection.getResponseCode() >= 300) {
	                throw new AppException("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
	            }
	            
	            inputStream = httpURLConnection.getInputStream();
	            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
	            reader = new BufferedReader(inputStreamReader);
	            
	            while ((tempLine = reader.readLine()) != null) {
	                resultBuffer.append(tempLine);
	            }
	            
	        } finally {
	            
	            if (outputStreamWriter != null) {
	                outputStreamWriter.close();
	            }
	            
	            if (outputStream != null) {
	                outputStream.close();
	            }
	            
	            if (reader != null) {
	                reader.close();
	            }
	            
	            if (inputStreamReader != null) {
	                inputStreamReader.close();
	            }
	            
	            if (inputStream != null) {
	                inputStream.close();
	            }
	            
	        }

	        return resultBuffer.toString();
		  }catch(Exception ex){
			  throw new AppException(ex.getMessage());
		  }
	    }
       
  
}
